package me.zxk.smartagriculture.repository;

import me.zxk.smartagriculture.entity.GreenhouseSensorData;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;

/**
 * 大棚传感器数据访问接口
 */
@Repository
public interface GreenhouseSensorDataRepository extends JpaRepository<GreenhouseSensorData, Long> {

    /**
     * 根据大棚ID分页查询传感器数据
     */
    Page<GreenhouseSensorData> findByGreenhouseIdOrderByRecordedAtDesc(Long greenhouseId, Pageable pageable);

    /**
     * 根据大棚ID和时间范围查询传感器数据
     */
    @Query("SELECT gsd FROM GreenhouseSensorData gsd WHERE gsd.greenhouseId = :greenhouseId " +
           "AND gsd.recordedAt BETWEEN :startTime AND :endTime ORDER BY gsd.recordedAt DESC")
    Page<GreenhouseSensorData> findByGreenhouseIdAndRecordedAtBetween(
            @Param("greenhouseId") Long greenhouseId,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime,
            Pageable pageable);

    /**
     * 获取大棚最新的传感器数据
     */
    @Query("SELECT gsd FROM GreenhouseSensorData gsd WHERE gsd.greenhouseId = :greenhouseId " +
           "ORDER BY gsd.recordedAt DESC LIMIT 1")
    GreenhouseSensorData findLatestByGreenhouseId(@Param("greenhouseId") Long greenhouseId);
}
